/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.polimi.deib.se2.meteocal.business.control;

import it.polimi.deib.se2.meteocal.business.boundary.LocationManager;
import it.polimi.deib.se2.meteocal.business.entity.Location;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import org.json.JSONException;

@Singleton
public class WeatherRoutine {
    
    
    @EJB
    LocationManager lm;
    
    @Schedule(second= "0", minute = "0", hour = "*/3", persistent = false)
    public void attachWeatherToLocations(){
        List<Location> allLocations;
        allLocations = lm.getLocations();
        
        DataWeatherImport dwi = new DataWeatherImport();
        
        for(Location loc : allLocations){
            StringBuilder weatherForecast = new StringBuilder();
            int codes[] = new int[16];
            try {
                codes = dwi.forecastWeatherAtCity(loc.getLocName());
            } catch (JSONException | IOException ex) {
                for(int i=0; i<16; i++){
                    codes[i] = -1;
                }            }
            for(int i=0; i<16; i++){
                String meteo = WeatherCodeConverter.convertCode(codes[i]);
                weatherForecast.append(meteo);
                if(i!=15)
                    weatherForecast.append(",");
                
            }
            
            loc.setWeather(weatherForecast.toString());
            lm.update(loc);
        }
    }
}
